/**
 * 
 */
package com.saceem.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.validation.ConstraintViolationException;

import com.saceem.beans.Imagenes;

/**
 * @author nbordenave
 * 
 */

@Stateless
@SuppressWarnings({ "unchecked" })
public class ImagenesDaoBean implements ImagenesDao {

	private static final Logger log = Logger.getLogger(ImagenesDaoBean.class
			.getName());

	@PersistenceContext(unitName = "JPA_UNIT_IMG")
	EntityManager em;

	@Override
	public Boolean salvarImagen(Imagenes img) throws Exception {
		// log.info("salvarImagen : " + img.toString());
		Boolean result = false;
		try {
			em.persist(img);
			result = true;
		} catch (ConstraintViolationException e) {
			// log.error("salvarImagen : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("salvarImagen : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	@Override
	public Imagenes modificarImagen(Imagenes img) throws Exception {
		// log.info("modificarImagen : " + img.toString());
		Imagenes tmpImg = null;
		try {
			tmpImg = em.merge(img);
			em.flush();

		} catch (ConstraintViolationException e) {
			// log.error("modificarImagen : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("modificarImagen : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return tmpImg;
	}

	@Override
	public Imagenes buscarImagen(String nombre, String empresa)
			throws Exception {

		try {
			// Imagenes tmpImg = (Imagenes)
			// em.createNamedQuery("findImageByName")
			// .setParameter("nombre", nombre)
			// .setParameter("empresa", empresa).getSingleResult();
			//
			// Facturas objTmp = (Facturas) em
			// .createNamedQuery("buscarFactura", Facturas.class)
			// .setParameter("Fac", f).getSingleResult();

			Imagenes tmpImg = (Imagenes) em
					.createNamedQuery("findImageByName", Imagenes.class)
					.setParameter("nom", nombre).setParameter("emp", empresa)
					.getSingleResult();

			return tmpImg;
		} catch (Exception e) {
			// log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
	}

	@Override
	public List<Imagenes> buscarImagenes() throws Exception {
		log.info("buscarImagenes()");
		List<Imagenes> result = null;
		try {
			result = (List<Imagenes>) em.createNamedQuery("findAllImages")
					.getResultList();
			log.info("Count Imagenes : " + result.size());
		} catch (Exception e) {
			// log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
		return result;
	}

}
